import classNames from "classnames";
import React, { useEffect, useRef, useState } from "react";

interface BaseFlyBoxProps {
  className?: string;
  strokeWidthOuter: number;
  strokeWidthInner: number;
  strokeOuter: string;
  strokeInner: string;
  stroke: string;
  dur: string;
  flyWidth: number;
}
type NativeFlyBoxProps = BaseFlyBoxProps & React.SVGAttributes<Element>;

//Partial可以把所有属性设置为可选
export type FlyBoxProps = Partial<NativeFlyBoxProps>;

export const FlyBox = (props: FlyBoxProps) => {
  const {
    className,
    strokeWidthOuter,
    strokeOuter,
    strokeInner,
    strokeWidthInner,
    flyWidth,
    dur,
  } = props;

  const classes = classNames("fly-box", className, {});
  // console.log("styleSheets", document.styleSheets);
  const ref = useRef() as any;
  const [path, setpath] = useState("");
  useEffect(() => {
    let width = ref.current.clientWidth;
    let height = ref.current.clientHeight;
    setpath(
      `M5 5 L${width - 5} 5 L${width - 5} ${height - 5} L5 ${height - 5} Z`
    );
  }, []);

  return (
    <div className={classes} style={{ width: "100%", height: "100%" }}>
      <svg width="100%" height="100%" ref={ref}>
        <defs>
          <path id="fly-box-path" d={path} fill="none"></path>
        </defs>
        <mask id="fly-box-mask">
          <radialGradient
            id="redial-gradient"
            cx="50%"
            cy="50%"
            fx="100%"
            fy="50%"
            r="50%"
          >
            <stop offset="0%" stopColor="#fff" stopOpacity={1}></stop>
            <stop offset="100%" stopColor="#fff" stopOpacity={0}></stop>
          </radialGradient>
          <circle r={flyWidth} cx="0" cy={0} fill="url(#redial-gradient)">
            <animateMotion
              dur={dur}
              path={path}
              rotate="auto"
              repeatCount="indefinite"
              calcMode={"linear"}
            ></animateMotion>
          </circle>
        </mask>
        <use
          href="#fly-box-path"
          stroke={strokeInner}
          strokeWidth={strokeWidthInner}
        ></use>
        <use
          href="#fly-box-path"
          stroke={strokeOuter}
          strokeWidth={strokeWidthOuter}
          mask="url(#fly-box-mask)"
        ></use>
      </svg>
      <div className="fly-box-childBox"> {props.children}</div>
    </div>
  );
};

FlyBox.defaultProps = {
  dur: "1s",
  flyWidth: 300,
  strokeWidthOuter: 10,
  strokeWidthInner: 1,
  strokeOuter: "#4fd2dd",
  strokeInner: "#235fa7",
};
export default FlyBox;
